import routesMap from '@/common/constant';
import loginApi from '@/common/api/login';
import store from '@/vuex/store';
import router from '@/router/index';
import nativeAction from '@/common/native';
/**
 * 权限验证方法
 * @module  common/util
 * @author dym
 */
const machCompanent = (arr, key) => {  //匹配载入组件
  let path = null;
  arr.forEach(item => {
    if (item.name === key) {
      path = item.component;
    }
  });
  return path;
};
const addAuthority = (arr, value, key) => { //加入权限和缓存
  let a = null;
  arr.forEach(item => {
    if (item.name === value) {
      a = item[key];
    }
  });
  return Boolean(a);
};

const getRoutes = (userInfo) => {  //获取动态路由
  let hashMenus = [];
  userInfo.forEach(key => {
    if (key.pageUrl) {
      hashMenus.push({
        path: key.pageUrl,
        name: key.pageName,
        component: machCompanent(routesMap.routesMap, key.pageName),
        meta: {
          requiresAuth: addAuthority(routesMap.routesMap, key.pageName, 'requiresAuth'),
          keepAlive: addAuthority(routesMap.routesMap, key.pageName, 'keepAlive')
        }
      });
    }
  });
  return hashMenus;
};

export default {
  getPermission () {
    let param = store.getters.store.storeCode ? '3' : '1'; //单店还是多店
    loginApi.getRoutes(param).then(res => {
      let hashMenu = getRoutes(res); //获取动态路由
      router.addRoutes(hashMenu.concat([
        {
          path: '*',
          redirect: '/login'
        }]));
    });
    //if (store.state.login.permission === '') {
    loginApi.getResources(param).then(res => {
      store.dispatch('setPermission', res);
    });
    //}
  },
  loginTask (res) {
    this.getPermission();
    store.dispatch('setStore', res.org);
    if (res.user) {
      nativeAction.setInfo(res.user);
    }
    router.push('/home/card');
  }
};
